package com.feicheng.common.token;

import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

@Component
public class TokenContainer extends HashMap<String, Token> {

	private static final long serialVersionUID = -3174406958551490091L;
	
	private static ThreadLocal<String> localTokenId = new ThreadLocal<String>();
	
	public static String getCurrentTokenId() {
		return localTokenId.get();
	}
	
	public static void setCurrentTokenId(String tokenId) {
		localTokenId.set(tokenId);
	}
	
	public static void removeCurrentTokenId() {
		localTokenId.remove();
	}

	public static final Integer TG = 30;
	
	public static Long currentMin() {
		return System.currentTimeMillis() / 1000 / 60;
	}

	public String getTokenId() {
        return UUID.randomUUID().toString()+System.currentTimeMillis();
    }

    public synchronized Token newToken() {
        Token token = new Token();
        token.setTokenId(this.getTokenId());
        token.setToken(new JSONObject());
        token.setMinute(currentMin());
        this.put(token.getTokenId(), token);
        return token;
    }

    public Token getToken(String tokenId) {

        Token token = null;

        if (!this.containsKey(tokenId)) {

        } else {
            token = this.get(tokenId);
        }

        return token;
    }

    public synchronized Token removeToken(String tokenId) {
        return this.remove(tokenId);
    }

    public synchronized void cleanContainer() {
        for (Iterator<Entry<String, Token>> it = this.entrySet().iterator(); it.hasNext();) {
            Entry<String, Token> entry = it.next();
            Token token = entry.getValue();
            if ((currentMin() - token.getMinute()) > TG) {
                it.remove();
            }
        }
    }



}
